package com.COMP3111H.project;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class My_Profile_Account_ChangePwd extends Activity implements View.OnClickListener{
	EditText oldPwd, newPwd, confirmPwd;
	//TextView errMsg;
	Button confirm,back;
	
	final int CHANGE_PWD_SUCCEED = 2;
	
	String sErrMsgNoErr = "";
	String sErrMsgOldInvalid = "Your old password is wrong. Please type again.";
	String sErrMsgNotMatch = "Your new password does not match. Please type again";
	String sErrMsgFailUpdate = "Fail to update. Please try it later.";

    private ProgressThread progThread;
    private ProgressDialog progDialog;
    Button menu;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_profile_account_changepwd);
		
		oldPwd = (EditText) findViewById(R.id.et_MyProfile_Account_Changepwd_OldPwd);
		newPwd = (EditText) findViewById(R.id.et_MyProfile_Account_Changepwd_NewPwd);
		confirmPwd = (EditText) findViewById (R.id.et_MyProfile_Account_ChangePwd_ConfirmPwd);
		
		//errMsg = (TextView) findViewById(R.id.tv_MyProfile_Account_ChangePwd_ChangePwd_ErrorMsg);
		
		confirm = (Button) findViewById(R.id.b_MyProfile_Account_ChangePwd_ConfirmChange);
		confirm.setOnClickListener(this);
		
		back = (Button) findViewById( R.id.b_MyProfile_Account_ChangePwd_Back);
		back.setOnClickListener(new View.OnClickListener(){

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
			
		});
		menu = (Button) findViewById(R.id.changepwd_menu);
	}
	
	@Override
    protected void onResume() {
		super.onResume();
		if (LoginUtility.checkLoginStatus(this)) {
			menu.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					 String[] choices={"Home","View My Profile","Help","Cancel"};  
					             AlertDialog dialog = new AlertDialog.Builder(My_Profile_Account_ChangePwd.this)  
					                     // .setIcon(android.R.drawable.btn_star)  
					                      .setTitle("Menu")  
					                      .setItems(choices, onselect_logged).create();  
					             dialog.show();  
				}
			});
		}
		else{
			menu.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					 String[] choices={"Home","Help","Cancel"};  
					             AlertDialog dialog = new AlertDialog.Builder(My_Profile_Account_ChangePwd.this)  
					                     // .setIcon(android.R.drawable.btn_star)  
					                      .setTitle("Menu")  
					                      .setItems(choices, onselect_not_logged).create();  
					             dialog.show();  
				}
			});
		}
	}

	OnClickListener onselect_logged = new OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			Intent myIntent;
			switch (which) {
			case 0:
				myIntent = new Intent(My_Profile_Account_ChangePwd.this, Home.class);
				startActivity(myIntent);
				break;
			case 1:
				myIntent = new Intent(My_Profile_Account_ChangePwd.this, My_Profile.class);
				startActivity(myIntent);
				break;
			case 2:
				myIntent = new Intent(My_Profile_Account_ChangePwd.this, Help.class);
				startActivity(myIntent);
				break;
			case 3:
				dialog.dismiss();
				break;
			}
		}
	};
	
	OnClickListener onselect_not_logged = new OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			Intent myIntent;
			switch (which) {
			case 0:
				myIntent = new Intent(My_Profile_Account_ChangePwd.this, Home.class);
				startActivity(myIntent);
				break;
			case 1:
				myIntent = new Intent(My_Profile_Account_ChangePwd.this, Help.class);
				startActivity(myIntent);
				break;
			case 2:
				dialog.dismiss();
				break;
			}
		}
	};

	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if(oldPwd.getText().toString().matches("") || newPwd.getText().toString().matches("")){
			Toast.makeText(
					My_Profile_Account_ChangePwd.this,
					"Missing Input",
					Toast.LENGTH_SHORT).show();
		}
		
		
		if ( !newPwd.getText().toString().equals(confirmPwd.getText().toString()) ){
			
			Toast.makeText(My_Profile_Account_ChangePwd.this, sErrMsgNotMatch, Toast.LENGTH_SHORT).show();
			return ;
		}
		
		String[] usernamePassword = LoginUtility.getUsernamePassword(My_Profile_Account_ChangePwd.this);
		String username = usernamePassword[0];
		
		List<NameValuePair> params = new ArrayList<NameValuePair>(3);
		Log.v("Bookwarm",username);
		params.add(new BasicNameValuePair("username", username));
		params.add(new BasicNameValuePair("newpassword", newPwd.getText().toString()));
		params.add(new BasicNameValuePair("oldpassword", oldPwd.getText().toString()));
		
		if(!NetworkUtility.inputCheck(username) || !NetworkUtility.inputCheck(newPwd.getText().toString()) || 
				!NetworkUtility.inputCheck(oldPwd.getText().toString()) )
				Toast.makeText(My_Profile_Account_ChangePwd.this,"There are special characters that are not allowed in your request", Toast.LENGTH_SHORT).show();
		else{
			showDialog(0);
			progThread = new ProgressThread( handler, params);
			progThread.start();
			
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id){
		case 0:
			progDialog = new ProgressDialog(this);
			progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progDialog.setMessage("Changing...");
			return progDialog;
		default:
			return null;
		}
	}
	
	final Handler handler = new Handler(){
		public void handleMessage(Message msg){
			removeDialog(0);
			String returnResult = msg.getData().getString("returnResult");
			if(returnResult.contains("change_password_successful")){
				Toast.makeText(
						My_Profile_Account_ChangePwd.this,
						"Password is successfully changed. A confirmation email is sent to your email address.",
						Toast.LENGTH_SHORT).show();
				finish();
			}
			else if(returnResult.contains("change_password_failed")){
				
				Toast.makeText(My_Profile_Account_ChangePwd.this, sErrMsgFailUpdate, Toast.LENGTH_SHORT).show();
			}
			else if(returnResult.contains("no_user_found")){
				
				Toast.makeText(My_Profile_Account_ChangePwd.this, sErrMsgOldInvalid, Toast.LENGTH_SHORT).show();
			}
			else{
				Toast.makeText(
						My_Profile_Account_ChangePwd.this,
						"Network Error.",
						Toast.LENGTH_SHORT).show();
			}
		}
	};
	
	private class ProgressThread extends Thread{
		Handler mHandler;
		List<NameValuePair> params;
		
		ProgressThread( Handler h, List<NameValuePair> p){
			mHandler = h;
			params = p;
		}
		
		
		@Override
		public void run(){
			String returnResult = NetworkUtility.sendHTTP(params, "http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/account_info_change_password.jsp");
			Message msg = mHandler.obtainMessage();
			Bundle b = new Bundle();
			b.putString("returnResult", returnResult);
			msg.setData(b);
			mHandler.sendMessage(msg);
			
		}
	}
}
